package com.dayuanit.booksystem.net;

import com.dayuanit.booksystem.BookServiceImpl;
import com.dayuanit.booksystem.Publisher;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * DYP协议 服务端
 */
public class Server {

    /**
     * 启动图书系统服务端
     */
    public static void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("图书管理系统系统成功! 端口号：" + 9999);

            //等待客户端的连接，当有客户端三次握手成功后，此方法才能继续往下执行
            Socket clientSocket = serverSocket.accept();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

            String msg = null;
            while (null != (msg = bufferedReader.readLine())) {
                System.out.println("接收客户端发送的消息：" + msg);

                //客户端发送的请求消息 要符合DYP协议规定
                String requestMessage = msg;
                //格式：方法名$入参1$入参2$....
//                addPublisher$清华出版社$南京市浦口区
                if (null == msg || msg.length() < 1) {
                    System.err.println("消息格式错误,请阅读DYP协议文档");
                    return;
                }

                String[] requestMessageArray = requestMessage.split("\\$");
                String methodName = requestMessageArray[0];

                //存放请求参数的集合
                List<Object> params = new ArrayList<>();

                for (int i=1; i<requestMessageArray.length; i ++) {
                    params.add(requestMessageArray[i]);
                }

                //方法名知道了，请求参数也知道了，那就调用service方法吧。
                BookServiceImpl bookService = new BookServiceImpl();

                //比较字符串 一定要用equals比较，否者的话会掉头发。
                //比较的时候，务必要用常量和变量进行比较，避免NPE异常。
                if ("addPublisher".equals(methodName)) {
                    if (params.size() != 2) {
                        System.out.println("请求参数不正确");
                        return;
                    }
                    bookService.addPublisher((String)params.get(0), (String)params.get(1));
                }

                if ("queryPublisherById".equals(methodName)) {
                    if (params.size() != 1) {
                        System.out.println("请求参数不正确");
                        return;
                    }
                    Publisher publisher = bookService.queryPublisher(Long.parseLong(params.get(0).toString()));
                    System.out.println(publisher);
                    bufferedWriter.write(publisher.toString());
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
